package ru.aslanov.schedule.server;

import ru.aslanov.schedule.model.Schedule;
import ru.aslanov.schedule.utils.XMLUtil;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * Created: Feb 8, 2010 6:06:28 PM
 *
 * @author Sergey Aslanov
 */
public class ExportScheduleServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        final String scheduleKey = request.getParameter("s");

        try {
            AccessManager.getInstance().checkScheduleAdmin(scheduleKey);
        } catch (AccessDeniedException e) {
            throw new ServletException(e);
        }

        final PersistenceManager pm = PMF.getThreadLocalPersistenceManager();

        try {
            final Schedule schedule = pm.getObjectById(Schedule.class, scheduleKey);

            response.setContentType("text/xml");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=schedule.xml");

            final Marshaller marshaller = XMLUtil.JAXB_CONTEXT.createMarshaller();
            marshaller.marshal(schedule, response.getWriter());
        } catch (JAXBException e) {
            throw new ServletException(e);
        } // finally {
        //    pm.close();
        //}

    }
}
